package com.tj.jinzao.base;

import android.os.Bundle;
import android.view.View;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 所有带自定义数据类型的刷新的listView的fragment基类
 * Created by wjy on 2016/3/25.
 */
public abstract class BaseDataListFragment<T, V extends BasePresenter, TH> extends BaseListFragment<T, V> {

    protected CopyOnWriteArrayList<TH> mData;
    protected final static String ARG_TAG_ID = "tagId";
    protected String mTag;//参数


    public static BaseDataListFragment newInstance(int loadId, String tagId, int layoutId, BaseDataListFragment fragment) {
        if (fragment != null) {
            Bundle args = new Bundle(3);
            args.putString(ARG_TAG_ID, tagId);
            args.putInt(ARG_LOAD_ID, loadId);
            args.putInt(ARG_LAYOUT_RES_ID, layoutId);
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTag = getArguments().getString(ARG_TAG_ID);
        mData = new CopyOnWriteArrayList();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        try {
            mListView.getAdapter().notifyDataSetChanged();
        } catch (Exception e) {
        }
    }

    @Override
    protected boolean hasData() {
        return mData != null && mData.size() > 0;
    }

    @Override
    public void onItemClick(View view, int position) {
        int newPosition = getDataIndex(position, mListView.getHeaderSize());
        if (newPosition != -1) {
            itemClicked(newPosition, mData.get(newPosition));
        }
    }

    @Override
    public void onItemLongClick(View view, int position) {
        int newPosition = getDataIndex(position, mListView.getHeaderSize());
        if (newPosition != -1) {
            itemLongClicked(newPosition, mData.get(newPosition));
        }
    }

    /**
     * 初始化Data
     */
    abstract protected void initData();

    abstract protected void itemClicked(int position, TH data);

    protected void itemLongClicked(int position, TH data) {

    }

    protected void showListView() {
        if (mData.size() != 0) {
            mListView.setVisibility(View.VISIBLE);
            mEmptyView.setVisibility(View.GONE);
        } else {
            setEmptyDataView();
        }
        mListView.getAdapter().notifyDataSetChanged();
    }

    /**
     * 点击item时，index需要减去headView
     *
     * @param position
     * @param headViewSize
     * @return
     */
    protected int getDataIndex(int position, int headViewSize) {
        position -= headViewSize;
        return (mData == null || position < 0 || position > mData.size() - 1) ? -1 : position;
    }

}